package com.yanyeori.framework.redis.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

/**
 * redis序列化工具
 *
 * @author chenkuan 2021/1/6
 */
@SuppressWarnings({"unchecked", "ConstantConditions"})
public class RedisSerializeUtil {

    private final RedisTemplate redisTemplate;

    public RedisSerializeUtil(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public byte[] rawKey(Object key) {
        Assert.notNull(key, "non null key required");
        if (keySerializer() == null && key instanceof byte[]) {
            return (byte[]) key;
        }
        return keySerializer().serialize(key);
    }

    public <HK> byte[] rawHashKey(HK hashKey) {
        Assert.notNull(hashKey, "non null hash key required");
        if (hashKeySerializer() == null && hashKey instanceof byte[]) {
            return (byte[]) hashKey;
        }
        return hashKeySerializer().serialize(hashKey);
    }

    public <HV> byte[] rawHashValue(HV value) {
        if (hashValueSerializer() == null & value instanceof byte[]) {
            return (byte[]) value;
        }
        return hashValueSerializer().serialize(value);
    }

    public byte[] rawValue(Object value) {
        if (valueSerializer() == null && value instanceof byte[]) {
            return (byte[]) value;
        }
        return valueSerializer().serialize(value);
    }

    public RedisSerializer keySerializer() {
        return redisTemplate.getKeySerializer();
    }

    public RedisSerializer valueSerializer() {
        return redisTemplate.getValueSerializer();
    }

    public RedisSerializer hashKeySerializer() {
        return redisTemplate.getHashKeySerializer();
    }

    public RedisSerializer hashValueSerializer() {
        return redisTemplate.getHashValueSerializer();
    }
}
